<template>
    <div class="register">
        <div class="container" v-if="!hasResult">
            <div class="header">
                <div class="navigator" v-if="stepActive !== 0" @click="confirm"> 
                    <gzg-icon name="arrow-left" size="18" color="#A8ABB2"></gzg-icon>
                    <span>返回注册首页</span>
                </div>
            </div>
            <div class="steps">
                <el-steps :active="stepActive" align-center >
                    <el-step>
                        <template #title>
                            <div>输入手机号</div>
                        </template>
                        <template #icon>
                            <div class="step-icon">1</div>
                        </template>
                    </el-step>
                    <el-step>
                        <template #title>
                            <div>输入验证码</div>
                        </template>
                        <template #icon>
                            <div class="step-icon">2</div>
                        </template>
                    </el-step>
                    <el-step>
                        <template #title>
                            <div>设置密码信息</div>
                        </template>
                        <template #icon>
                            <div class="step-icon">3</div>
                        </template>
                    </el-step>

                </el-steps>
            </div>
            <div class="step-panel" v-if="stepActive === 0">
                <div class="first">
                    <div class="title">欢迎注册ERP</div>
                    <div class="desc">手机号码将用于登录账户、账号管理验证等</div>
                    <el-form ref="phoneFormRef" 
                             :model="phoneForm"
                             :rules="phoneFormRules"
                             class="login-form">
                        <el-form-item prop="mobile">
                            <el-input v-model="phoneForm.mobile" placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <div class="checkbox-wrap">
                            <el-checkbox v-model="isAgree">
                                <template #default>
                                    <div class="checkbox-text">
                                        <span class="text">我已阅读并同意</span>
                                        <span class="link" @click.stop="goServiceAgreement">服务协议</span>
                                        <span class="text">和</span>
                                        <span class="link" @click.stop="goPrivacyAgreement">隐私协议</span>
                                    </div>
                                </template>
                            </el-checkbox>
                        </div>
                        <el-button :disabled="!(Boolean(phoneForm.mobile))" 
                                    @click="submitForm(phoneFormRef)"
                                    class="btn" 
                                    type="primary">下一步</el-button>
                        <div class="tip">
                            <span class="text">已有账号？</span>
                            <span class="link" @click="goback">去登录</span>
                        </div>
                    </el-form>
                </div>
                
            </div>
            <div class="step-panel" v-if="stepActive === 1">
                <div class="second">
                    <div class="title">输入手机号验证码</div>
                    <div class="desc">验证码已发送至 +86{{getMobile()}}</div>
                    <div class="captcha-wrap" :class="{'error': errorText}">
                        <input v-for="(item,index) in captchaList" 
                               :key="index" 
                               maxlength="1" 
                               type="text" 
                               class="captcha-input" 
                               v-model="item.value"
                               :ref="(el) => setCaptchaRef(el, index)"
                               @keyup.delete="captchaDel(item, index)"
                               @input="captchaInput(item, index)"
                               :autofocus="item.focus" />
                    </div>
                    <div class="error-msg">{{errorText}}</div>
                    <div class="tips">
                        <span class="text">未收到验证码？</span>
                        <span class="gray" v-if="intervalTime > 0">{{intervalTime}}s后重新获取</span>
                        <span class="link" v-else @click="countDown">重新获取</span>
                    </div>
                </div>
            </div>
            <div class="step-panel" v-if="stepActive === 2">
                <div class="third">
                    <div class="title">设置账号信息</div>
                    <div class="desc">密码长度6-16位，需同时包含数字/字母/特殊符号，两种及以上组合</div>
                    <el-form ref="userFormRef"
                             :model="userForm"
                             :rules="userFormRules"
                             class="login-form">
                        <el-form-item prop="password">
                            <el-input v-model="userForm.password" :type="passwordShow ? 'text'  : 'password'" placeholder="请设置登录密码">
                                <template #suffix>
                                    <el-icon @click.stop="passwordShow = !passwordShow" style="cursor: pointer;">
                                        <Hide v-if="!passwordShow" /> 
                                        <View v-else />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="rePassword">
                            <el-input v-model="userForm.rePassword" :type="rePasswordShow ? 'text' : 'password'" placeholder="请确认登录密码">
                                <template #suffix>
                                    <el-icon @click.stop="rePasswordShow = !rePasswordShow" style="cursor: pointer;">
                                        <Hide v-if="!rePasswordShow" /> 
                                        <View v-else />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="companyName">
                            <el-input v-model="userForm.companyName" clearable placeholder="请输入公司名称(选填)"></el-input>
                        </el-form-item>
                        <el-button :disabled="!(Boolean(userForm.password) && Boolean(userForm.rePassword))"
                                   class="btn mt22"
                                   @click="handleRegister(userFormRef)"
                                   type="primary">注册</el-button>
                    </el-form>
                </div>
            </div>
        </div>
        <div class="result" v-else></div>
    </div>
</template>
<script lang="ts" setup>
import {ref, reactive, nextTick} from 'vue'
import {ElMessageBox, ElMessage} from 'element-plus'
import { Hide,View } from '@element-plus/icons-vue'

import {sendRegisterCaptcha, validRegisterCaptcha, register} from 'services/system'

import type { FormInstance, FormRules } from 'element-plus'

const stepActive = ref(0)
const hasResult = ref(false);

const emits = defineEmits(['goback'])

const confirm = () => {
    ElMessageBox.confirm('返回注册首页将取消注册，是否返回？','提示',{
        confirmButtonText:'取消注册',
        cancelButtonText:'继续注册',
        center:true,
        closeOnClickModal:false
    }).then((res) => {
        goback()

    }).catch(() => {
    })
}

const goback = () => {
    emits('goback')
}

// first panel 
const isAgree = ref(false)

const phoneFormRef = ref<FormInstance>()

const phoneForm = reactive({
    mobile:''
});

const checkPhone = (rule:any,value:any,callback:any) => {
    let reg = /^1[0-9]{10}$/;
    
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const phoneFormRules = reactive<FormRules>({
    mobile:[{validator:checkPhone, trigger:'blur'}],
})

const goServiceAgreement = () => {

}

const goPrivacyAgreement = () => {

}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (!isAgree.value) {
                ElMessage({
                    message:'请先勾选协议',
                    type:'error'
                })
                return;
            }  
            sendRegisterCaptcha(phoneForm).then((res:any) => {
                stepActive.value = 1;
                countDown()
            }).catch(err => {
                console.log(err)
            })
            
            console.log('submit')
        } else {
            console.log('error submit', fields)
        }
    }) 
}

// second panel

const getMobile = () => {
	return phoneForm.mobile.replace(/^(\d{3})\d{4}(\d{4})$/, `$1****$2`)
}

const intervalTime = ref(0)
let timer:any;

const errorText = ref('')

interface captcha {
    value:number | null,
    focus:boolean
}

const countDown = () => {
    intervalTime.value = 60;
    timer = setInterval(() => {
        if (intervalTime.value == 0) {
            clearInterval(timer)
            
        }
        intervalTime.value--
    }, 1000)
}

const captchaList = reactive<captcha[]>([{
    value: null,
    focus:true,
},{
    value: null,
    focus:false,
},{
    value: null,
    focus:false,
},{
    value: null,
    focus:false,
},{
    value: null,
    focus:false,
},{
    value: null,
    focus:false,
}])

let refs = <HTMLElement[]>[]

const setCaptchaRef = (el:HTMLElement,index:number) => {
    refs[index] = el
}

const captchaDel = (captcha:captcha, index:number) => {
    if (index == 0) {
        return;
    }

    refs[index]?.blur();
    refs[index - 1]?.focus();
}

const captchaInput =  (captcha:captcha, index:number) => {
    if (!captchaList[index].value) {
        return;
    }
    refs[index]?.blur()
    if (index + 1 == captchaList.length) {
        captchaSubmit()
        return
    }  else {
        refs[index + 1]?.focus()
    } 
}

const captchaSubmit = () => {
    let captchaCode = captchaList.map(obj => {
        return obj.value
    }).join('');
    validRegisterCaptcha({
        mobile:phoneForm.mobile,
        sms_code:captchaCode
    }).then(res => {
        clearInterval(timer);
        stepActive.value = 2;
    }).catch(err => {
        errorText.value = '验证码错误，请重新输入'
    })
}

// third panel
const userFormRef = ref<FormInstance>()

const passwordShow = ref(false)
const rePasswordShow = ref(false)

const userForm = reactive({
    password:'',
    rePassword:'',
    companyName:''
});

const checkPassword = (rule:any,value:any,callback:any) => {
    var reg = /(?!^[0-9]+$)(?!^[a-z]+$)(?!^[A-Z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]/

    if (value === '') {
        callback(new Error('请输入登录密码'))
    } else if (value.length < 6) {
        callback(new Error('密码最少6位'))
    } else if (value.length > 16) {
        callback(new Error('密码最多16位'))

    } else if (!reg.test(value)) {
        callback(new Error('密码需同时包含数字/字母/特殊符号，两种及以上组合'))

    } else {
        callback()
    }
}

const checkRePassword = (rule:any,value:any,callback:any) => {
    if (value != userForm.password){
        callback(new Error('与登录密码不一致'))

    } else {
        callback()
    }
}

const userFormRules = reactive<FormRules>({
    password:[{
        validator:checkPassword, 
        trigger:'blur'}],
    rePassword:[{
        validator:checkRePassword,
        trigger:'blur'}],
})

const handleRegister = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            register({
                mobile:phoneForm.mobile,
                password:userForm.password,
                confirm_password:userForm.rePassword,
                company_name:userForm.companyName
            }).then(res => {
                ElMessage.success('注册成功！')
                goback()
            })
        } else {
            console.log('error submit', fields)
        }
    }) 
}

</script>
<style lang="scss">
.register{
    .header{
        height: 80px;
        width: 100%;
        display: flex;
        align-items: center;
        box-sizing: border-box;
        padding-left: 16px;

        .navigator{
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #a8abb2;
            cursor: pointer;

            span{
                margin-left: 3px;
            }
        }
    }

    .steps{
        height: 54px;
    }

    .el-step__head{
        .el-step__line{
            height: 1px;
            background-color: #E4E7ED;
        }

        &.is-process{
           .step-icon{
                background-color: #2770EE;
                border-color: #2770EE;
                color: #fff;
           }
        }

        &.is-finish{
            .el-step__line{
                background-color: #2770EE;
            }

            .step-icon{
                background-color: #fff;
                border-color: #2770EE;
                color: #2770EE;
           }
        }
    }

    .el-step__main{
        margin-top: 8px;

        .el-step__title{
            font-weight: 500;
            font-size: 14px;
            line-height: 22px;
            height: 22px;

            &.is-process{
                color: #2770EE;
                font-weight: 600;
            }
        }       
    }

    .step-icon{
        width: 24px;
        height: 24px;
        border:2px solid #C0C4CC;
        border-radius: 50%;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
    }

    .step-panel{
        .title{
            margin-top: 64px;
            font-size: 20px;
            font-weight: 600;
            color: #303133;
            line-height: 28px;
            text-align: center;
        }

        .desc{
            margin-top: 10px;
            font-size: 14px;
            font-weight: 400;
            color: #909399;
            line-height: 22px;
            text-align: center;
        }
    }

    .login-form{
        margin: 40px auto 0 auto;
        width: 360px;

        .btn{
            margin-top: 40px !important;

            &.mt22{
                margin-top: 22px !important;
            }
        }
    }

    .first{
        .checkbox-wrap{
            text-align: center;

            .checkbox-text{
                font-size: 14px;

                .text{
                    color: #606266;
                }

                .link{
                    color: #2770EE;
                    margin: 0 4px;
                    cursor: pointer;
                }
            }
        }

        .tip{
            font-size: 14px;
            text-align: center;
            margin-top: 21px;

            .link{
                color: #2770EE;
                cursor: pointer;
                font-weight: 500;
            }
        }
    }

    .second{
        display: flex;
        flex-direction: column;
        align-items: center;
        .captcha-wrap{
            width: 368px;
            margin: 40px auto 0 auto;
            display: flex;
            justify-content: space-between;

            .captcha-input{
                height: 48px;
                width: 48px;
                border-radius: 8px;
                border:1px solid #dcdfe6;
                text-align: center;
                box-sizing: border-box;
                font-size: 18px;
                color: #303133;
                font-weight: 500;
            }

            &.error{
                .captcha-input{
                    border-color: #F56C6C;

                    &:focus-visible {
                        outline: 1px solid #F56C6C;
                    }
                }
            }
        }

        .error-msg{
            height: 40px;
            width: 360px;
            line-height: 40px;
            font-size: 12px;
            font-weight: 500;
            color: #F56C6C;
            text-align: center;
        }

        .tips{
            height: 48px;
            font-size: 14px;

            .text{
                color: #000;
            }

            .gray{
                color: #C0C4CC;
                font-weight: 500;
            }

            .link{
                color: #2770EE;
                font-weight: 500;
            }
            
        }
    }
}
</style>